package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.dto.AfterSaleMaintenanceAddDTO;
import com.ruoyi.system.dto.AfterSaleMaintenanceQueryDTO;
import com.ruoyi.system.dto.AfterSaleMaintenanceUpdateDTO;
import com.ruoyi.system.entity.AfterSaleMaintenanceDO;
import com.ruoyi.system.mapper.AfterSaleMaintenanceMapper;
import com.ruoyi.system.mapper.ProjectMapper;
import com.ruoyi.system.service.IAfterSaleMaintenanceService;
import com.ruoyi.system.vo.AfterSaleMaintenanceVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 售后维护服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
public class AfterSaleMaintenanceServiceImpl extends ServiceImpl<AfterSaleMaintenanceMapper, AfterSaleMaintenanceDO> 
        implements IAfterSaleMaintenanceService {

    @Resource
    private AfterSaleMaintenanceMapper afterSaleMaintenanceMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Override
    public List<AfterSaleMaintenanceVO> selectAfterSaleMaintenanceList(AfterSaleMaintenanceQueryDTO queryDTO, int pageNum, int pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<AfterSaleMaintenanceDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(queryDTO.getProjectId() != null, AfterSaleMaintenanceDO::getProjectId, queryDTO.getProjectId())
                .like(StringUtils.isNotBlank(queryDTO.getMaintenanceName()), AfterSaleMaintenanceDO::getMaintenanceName, queryDTO.getMaintenanceName())
                .eq(StringUtils.isNotBlank(queryDTO.getContactPhone()), AfterSaleMaintenanceDO::getContactPhone, queryDTO.getContactPhone())
                .eq(queryDTO.getUrgencyLevel() != null, AfterSaleMaintenanceDO::getUrgencyLevel, queryDTO.getUrgencyLevel())
                .eq(StringUtils.isNotBlank(queryDTO.getRepairType()), AfterSaleMaintenanceDO::getRepairType, queryDTO.getRepairType())
                .eq(queryDTO.getDesignerId() != null, AfterSaleMaintenanceDO::getDesignerId, queryDTO.getDesignerId())
                .eq(queryDTO.getStatus() != null, AfterSaleMaintenanceDO::getStatus, queryDTO.getStatus())
                .eq(StringUtils.isNotBlank(queryDTO.getCreatedBy()), AfterSaleMaintenanceDO::getCreatedBy, queryDTO.getCreatedBy())
                .ge(StringUtils.isNotBlank(queryDTO.getBeginTime()), AfterSaleMaintenanceDO::getCreateTime, queryDTO.getBeginTime())
                .le(StringUtils.isNotBlank(queryDTO.getEndTime()), AfterSaleMaintenanceDO::getCreateTime, queryDTO.getEndTime())
                .orderByDesc(AfterSaleMaintenanceDO::getCreateTime);

        // 查询数据
        List<AfterSaleMaintenanceDO> records = afterSaleMaintenanceMapper.selectList(queryWrapper);

        // 转换为VO
        List<AfterSaleMaintenanceVO> voList = records.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return voList;
    }

    @Override
    public AfterSaleMaintenanceVO selectAfterSaleMaintenanceById(Long id) {
        AfterSaleMaintenanceDO entity = afterSaleMaintenanceMapper.selectById(id);
        if (entity == null) {
            throw new ServiceException("售后维护记录不存在");
        }
        return convertToVO(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertAfterSaleMaintenance(AfterSaleMaintenanceAddDTO addDTO) {
        AfterSaleMaintenanceDO entity = new AfterSaleMaintenanceDO();
        BeanUtils.copyProperties(addDTO, entity);

        // 处理保修图片
        if (addDTO.getRepairImages() != null && !addDTO.getRepairImages().isEmpty()) {
            entity.setRepairImages(JSON.toJSONString(addDTO.getRepairImages()));
        }

        // 设置默认状态为待处理
        entity.setStatus(1);
        entity.setCreatedBy(SecurityUtils.getUsername());
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());

        return afterSaleMaintenanceMapper.insert(entity) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAfterSaleMaintenance(AfterSaleMaintenanceUpdateDTO updateDTO) {
        // 检查记录是否存在
        AfterSaleMaintenanceDO existEntity = afterSaleMaintenanceMapper.selectById(updateDTO.getId());
        if (existEntity == null) {
            throw new ServiceException("售后维护记录不存在");
        }

        AfterSaleMaintenanceDO entity = new AfterSaleMaintenanceDO();
        BeanUtils.copyProperties(updateDTO, entity);

        // 处理保修图片
        if (updateDTO.getRepairImages() != null && !updateDTO.getRepairImages().isEmpty()) {
            entity.setRepairImages(JSON.toJSONString(updateDTO.getRepairImages()));
        }

        entity.setUpdateTime(LocalDateTime.now());

        return afterSaleMaintenanceMapper.updateById(entity) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAfterSaleMaintenanceByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("删除ID列表不能为空");
        }
        return afterSaleMaintenanceMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAfterSaleMaintenanceById(Long id) {
        if (id == null) {
            throw new ServiceException("删除ID不能为空");
        }
        return afterSaleMaintenanceMapper.deleteById(id) > 0;
    }

    /**
     * 转换为VO对象
     */
    private AfterSaleMaintenanceVO convertToVO(AfterSaleMaintenanceDO entity) {
        AfterSaleMaintenanceVO vo = new AfterSaleMaintenanceVO();
        BeanUtils.copyProperties(entity, vo);

        // 处理保修图片
        if (StringUtils.hasText(entity.getRepairImages())) {
            try {
                List<String> images = JSON.parseArray(entity.getRepairImages(), String.class);
                vo.setRepairImages(images);
            } catch (Exception e) {
                // 解析失败时设置为空列表
                vo.setRepairImages(new ArrayList<>());
            }
        }

        // 设置描述字段
        vo.setUrgencyLevelDesc(getUrgencyLevelDesc(entity.getUrgencyLevel()));
        vo.setStatusDesc(getStatusDesc(entity.getStatus()));

        // 设置项目名称
        if (entity.getProjectId() != null) {
            try {
                com.ruoyi.system.domain.Project project = projectMapper.selectById(entity.getProjectId());
                if (project != null) {
                    vo.setProjectName(project.getProjectName());
                }
            } catch (Exception e) {
                // 获取项目名称失败时忽略
            }
        }

        return vo;
    }

    /**
     * 获取紧急程度描述
     */
    private String getUrgencyLevelDesc(Integer urgencyLevel) {
        if (urgencyLevel == null) {
            return "";
        }
        switch (urgencyLevel) {
            case 1:
                return "低";
            case 2:
                return "中";
            case 3:
                return "高";
            case 4:
                return "紧急";
            default:
                return "";
        }
    }

    /**
     * 获取状态描述
     */
    private String getStatusDesc(Integer status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case 1:
                return "待处理";
            case 2:
                return "处理中";
            case 3:
                return "已完成";
            case 4:
                return "已取消";
            default:
                return "";
        }
    }
}
